package com.swhy

import java.net.URI
import java.util.UUID

import com.utils._
import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.fs.{FileSystem, Path}
import org.apache.spark.sql.hive.HiveContext
import org.apache.spark.{SparkConf, SparkContext}
import org.codehaus.jackson.map.ObjectMapper


object ChgeMgrInfo {
  def main(args: Array[String]): Unit = {
    if (args.length != 3) {
      println(
        """
          |com.swhy.CompanyInfo
          |params:
          | InputDate    刷数日期
          | OutputPath   输出路径
        """.stripMargin)
      sys.exit()
    }
    val conf = new Configuration()
    val Array(inputDt, outputPath, splitNum) = args
    val sparkConf = new SparkConf().setAppName(this.getClass.getName)
    val sc = new SparkContext(sparkConf)
    val hiveContext = new HiveContext(sc)
//改下方的sql为需要装换成jason的sql
    val allcompany =s"""
        |select
        |A.mgr_cd as mgr_cd,
        |A.brch_org_cd as brch_org_cd,
        |B.brch_org_level as brch_org_level_cd,
        |A.role_cd as role_cd
        |from
        |app_data.app_chge_mgr_info A
        |left join
        |cde_data.t99_brch_org_level_cd B
        |on A.brch_org_cd = B.brch_org
        |where A.biz_date=${inputDt}
      """.stripMargin
    print(allcompany)
    val frame = hiveContext.sql(allcompany)
    val result = frame.rdd.map(x => {
      var cominfo = new StringBuilder()

      val mgr_cd = x.getAs[String]("mgr_cd")
      val brch_org_cd = x.getAs[String]("brch_org_cd")
      val brch_org_level_cd = x.getAs[String]("brch_org_level_cd")
      val role_cd = x.getAs[String]("role_cd")


      val _id = new ID()
      val index = new Index()
      val companyInfo = new ChgeMgrInfo()

      _id.set_id(UUID.randomUUID().toString)
      index.setIndex(_id)
      companyInfo.setMgrCd(mgr_cd)
      companyInfo.setBrchOrgCd(brch_org_cd)
      companyInfo.setBrchOrgLevelCd(brch_org_level_cd)
      companyInfo.setRoleCd(role_cd)

      val mapper = new ObjectMapper()

      val indexJson = mapper.writeValueAsString(index) //企业自增编码json串
      val companyInfoJson = mapper.writeValueAsString(companyInfo) //企业信息串

      cominfo = cominfo.append(indexJson + "\n" + companyInfoJson) //json结果串
      cominfo.toString()
    })
    val path = new Path(outputPath) //创建文本输出路径
    val fs = FileSystem.get(URI.create(outputPath), conf)
    if (fs.exists(path)) {
      fs.delete(path, true)
    }
    result.coalesce(splitNum.toInt,true).saveAsTextFile(outputPath)
    sc.stop()
  }
}
